﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RedisClientCluster
{
    public class RedisNodesInit
    {
        static Random ran = new Random();
        /** key's count */
        private const int EXE_TIMES = 100000;

        private const int NODE_COUNT = 3;

        private const int VIRTUAL_NODE_COUNT = 300;

        public static List<string> nodes = new List<string>();
        public static string GetRedisNode( string key)
        {
            RedisNodesInit test = new RedisNodesInit();
            Dictionary<string, int> nodeRecord = new Dictionary<string, int>();
            List<string> allNodes = test.getNodes(NODE_COUNT);
            KetamaNodeLocator locator = new KetamaNodeLocator(allNodes, VIRTUAL_NODE_COUNT); 
            string node = locator.GetPrimary(key);
            return node;
        }

        public static string GetRedisNode_Bak(string key)
        {
            RedisNodesInit test = new RedisNodesInit();
            Dictionary<string, int> nodeRecord = new Dictionary<string, int>();
            List<string> allNodes = test.getNodes(NODE_COUNT);
            KetamaNodeLocator locator = new KetamaNodeLocator(allNodes, VIRTUAL_NODE_COUNT);
            string node = locator.GetPrimary_Bak(key);
            return node;
        }





        /**
         * Gets the mock node by the material parameter
         * 
         * @param nodeCount 
         * 		the count of node wanted
         * @return
         * 		the node list
         */
        private List<string> getNodes(int nodeCount)
        {  
            //在应用时，这里会添入memcached server的IP端口地址
            nodes.Add("192.168.235.101:6379");
            nodes.Add("192.168.235.102:6379");
            nodes.Add("192.168.235.103:6379");
            return nodes;
        }

        /**
         *	All the keys	
         */
        private List<String> getAllStrings()
        {
            List<string> allStrings = new List<string>(EXE_TIMES);

            for (int i = 0; i < EXE_TIMES; i++)
            {
                allStrings.Add(generateRandomString(ran.Next(50)));
            }

            return allStrings;
        }

        /**
         * To generate the random string by the random algorithm
         * <br>
         * The char between 32 and 127 is normal char
         * 
         * @param length
         * @return
         */
        private String generateRandomString(int length)
        {
            StringBuilder sb = new StringBuilder(length);

            for (int i = 0; i < length; i++)
            {
                sb.Append((char)(ran.Next(95) + 32));
            }

            return sb.ToString();
        }
    }
}
